import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:map_launcher/map_launcher.dart';
import 'package:tracker/common/constants/app_constants.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/permission/permission_manager.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/home/location/mixin/location_page_mixin.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:tracker/pages/home/location/model/today_mileage_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/device_utils.dart';
import 'package:tracker/utils/location_utils.dart';
import 'package:tracker/utils/num_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

class LocationPage extends ConsumerStatefulWidget {
  const LocationPage({super.key});

  @override
  ConsumerState<LocationPage> createState() => _LocationPageState();
}

class _LocationPageState extends ConsumerState<LocationPage> with LocationPageMixin {
  final GlobalKey bottomViewKey = GlobalKey();
  double bottomViewHeight = 212;

  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();

  // 是否定位到设备位置或者手机位置
  bool isLocation = false;

  BMFMapOptions mapOptions = BMFMapOptions(
      center: BMFCoordinate(39.917215, 116.380341),
      zoomLevel: 17,
      mapPadding: BMFEdgeInsets(left: 30, top: 0, right: 30, bottom: 0));

  BMFMapController? myMapController;
  BMFMarker? deviceMarker;

  /// 今日里程
  String todayMileage = '0';

  // 多少秒刷新一次
  int refreshTime = 10;
  int countDown = 10;
  final timerUtil = TimerUtil(mTotalTime: 10 * 1000);

  // 点击位置，1:设备位置 2:手机位置 0: 未获取到经纬度时获取显示当前定位的位置
  int clickLocationType = 1;

  onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;
    myMapController!.showUserLocation(true);
    myMapController?.setMapDidLoadCallback(callback: () async {
      XLogger.debug('地图加载完成');
      final deviceInfo = ref.read(deviceInfoProvider);
      if (deviceInfo.isNineDevice == true) {
        // 定位到手机位置
        isLocation = true;
        await _myLocPlugin.stopLocation();
        _startLocation();
      }
    });
    myMapController?.updateMapOptions(BMFMapOptions(
      logoPosition: BMFLogoPosition.LeftTop,
      showZoomControl: false,
    ));
    _fetchDeviceLocation();
  }

  /// 获取设备实时信息
  Future<void> _fetchDeviceLocation() async {
    XLogger.info('获取设备实时信息');
    // 10秒的时候不允许点击刷新
    if (timerUtil.isActive() && countDown >= 9) {
      return;
    }
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == true) {
      MonitorData fakeMonitorData = MonitorData();
      fakeMonitorData.deviceName = deviceInfo.deviceName;
      fakeMonitorData.batteryPercentage = 100;
      fakeMonitorData.csq = 30;
      fakeMonitorData.deviceStatus = 2; // 离线
      fakeMonitorData.motionStateText = '静止';
      fakeMonitorData.workModeName = '智能模式';
      fakeMonitorData.locationType = 1;
      fakeMonitorData.altitude = 0;
      fakeMonitorData.lastCommunicationTime =
          DateUtil.formatDate(DateTime.now().subtract(const Duration(seconds: 10)), format: 'yyyy-MM-dd HH:mm:ss');
      setState(() {
        monitorData = fakeMonitorData;
      });
      // 解析地址
      getNineDeviceAddress();
      // 开启倒计时
      countDown = refreshTime;
      timerUtil.updateTotalTime(refreshTime * 1000);
      return;
    }

    _fetchDeviceTodayMileage(deviceInfo.imei!).then((value) {
      if (mounted) {
        setState(() {
          var mm = value / 1000;
          // 格式化，最多保留两位小数，小数点后为0就不显示
          todayMileage = NumUtils.formatNum(mm);
        });
      }
    });
    final res = await get<MonitorDataResp, MonitorDataResp>('/monitor/info',
        queryParameters: {'imei': deviceInfo.imei}, decodeType: MonitorDataResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        // 测试经纬度为空
        setState(() {
          monitorData = resp.data;
        });
        if (resp.data?.latitude != null) {
          hasLocation = true;
          setState(() {});
          _drawDeviceMarker(resp.data!.latitude!, resp.data!.longitude!);
        } else {
          hasLocation = false;
          // 返回的实时信息中没有经纬度，默认为基站定位
          monitorData?.locationType = 3;
          // 经纬度为空，定位到手机位置，解析当前经纬度
          XLogger.info('phoneAddress: $phoneAddress');
          if (phoneAddress != null) {
            monitorData?.longitude = phoneLocation?.longitude;
            monitorData?.latitude = phoneLocation?.latitude;
            monitorData?.address = phoneAddress;
            setState(() {});
            _drawDeviceMarker(monitorData!.latitude!, monitorData!.longitude!);
          } else {
            clickLocationType = 0;
            _startLocation();
          }
        }
        // 开启倒计时
        countDown = refreshTime;
        timerUtil.updateTotalTime(refreshTime * 1000);
      } else {
        if (resp.msg != null) {
          ToastUtils.showToast(resp.msg!);
        }
      }
      return null;
    }, failure: (String msg, int code) {
      XLogger.error('获取设备实时信息失败：msg: $msg, code: $code');
    });
  }

  _drawDeviceMarker(double latitude, double longitude) {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == true) {
      return;
    }
    myMapController?.setCenterCoordinate(BMFCoordinate(latitude, longitude), true);
    if (deviceMarker == null) {
      final double scale = _getMarkerIconScale();
      deviceMarker = BMFMarker.icon(
        position: BMFCoordinate(latitude, longitude),
        icon: getDeviceIcon(monitorData?.deviceStatus),
        identifier: 'deviceMarker',
        scaleX: scale,
        scaleY: scale,
      );
      myMapController?.addMarker(deviceMarker!);
    } else {
      deviceMarker?.updatePosition(BMFCoordinate(latitude, longitude));
      deviceMarker?.updateIcon(getDeviceIcon(monitorData?.deviceStatus));
    }
  }

  /// 获取设备今日里程
  Future<num> _fetchDeviceTodayMileage(String imei) async {
    final res = await post<TodayMileageResp, TodayMileageResp>('/device/getTodayMileage',
        data: {'imei': imei}, decodeType: TodayMileageResp());
    return res.when(success: (resp) {
      if (resp.code == 200) {
        return resp.data ?? 0;
      }
      return 0;
    }, failure: (String msg, int code) {
      XLogger.error('获取设备今日里程：msg: $msg, code: $code');
      return 0;
    });
  }

  /// 获取marker图标缩放比例
  double _getMarkerIconScale() {
    final density = ScreenUtil.getScreenDensity(context);
    XLogger.info('density: $density');
    final double scale = 1 + (density) / 10;
    XLogger.info('scale: $scale');
    return scale;
  }

  /// 构建设备信息卡片
  Widget _buildInfoCard() {
    const fontSize = 12.0;
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppTheme.themeConfig.greyBgColor.withOpacity(0.5),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 第1行：状态和电量信号
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(child: _buildDeviceStatusView(fontSize)),
              Row(
                children: [
                  _buildBatteryInfo(fontSize),
                  _buildCsqInfo(fontSize),
                ],
              )
            ],
          ),
          const SizedBox(height: 8),
          // 分割线
          Container(height: 1, color: AppTheme.themeConfig.dividerColor),
          const SizedBox(height: 8),
          // 设备信息网格
          Wrap(
            spacing: 12,
            runSpacing: 6,
            children: [
              _buildInfoItem(Icons.devices, '设备名称', monitorData?.deviceName ?? ''),
              _buildInfoItem(Icons.access_time, '静止时长', _getStaticTime()),
              _buildInfoItem(Icons.directions_bike, '今日里程', '${todayMileage}km'),
              _buildInfoItem(Icons.location_on, '定位模式', monitorData?.workModeName ?? ''),
            ],
          ),
          const SizedBox(height: 6),
          _buildLocationModeInfo(),
          const SizedBox(height: 6),
          _buildInfoItem(Icons.access_time_filled, '通讯时间', monitorData?.lastCommunicationTime ?? ''),
          const SizedBox(height: 6),
          _buildAddressInfo(),
        ],
      ),
    );
  }

  Widget _buildInfoItem(IconData icon, String label, String value) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 14, color: AppTheme.themeConfig.primaryColor),
        const SizedBox(width: 4),
        Text(
          '$label: ',
          style: TextStyle(
            fontSize: 12,
            color: AppTheme.themeConfig.secondaryTextColor,
            fontWeight: FontWeight.w500,
          ),
        ),
        Flexible(
          child: Text(
            value,
            style: TextStyle(
              fontSize: 12,
              color: AppTheme.themeConfig.primaryTextColor,
              fontWeight: FontWeight.w600,
            ),
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }

  /// 电量
  _buildBatteryInfo(double fontSize) {
    if (monitorData?.batteryPercentage == null) {
      return Container();
    }
    return Row(
      children: [
        Image.asset(
          _getBatteryImage(monitorData?.batteryPercentage),
          width: 28,
          height: 20,
          fit: BoxFit.fitWidth,
        ),
        const SizedBox(width: 4),
        Text('${monitorData?.batteryPercentage ?? ''}%',
            style: TextStyle(fontSize: fontSize, color: AppTheme.themeConfig.primaryTextColor)),
        const SizedBox(width: 12),
      ],
    );
  }

  /// 信号
  _buildCsqInfo(double fontSize) {
    if (monitorData?.csq == null) {
      return Container();
    }
    return Row(
      children: [
        Image.asset(
          _getCsqLevelImage(monitorData?.csq),
          width: 24,
          height: 16,
          fit: BoxFit.fitWidth,
        ),
        const SizedBox(width: 4),
        Text('${monitorData?.csq ?? ''}',
            style: TextStyle(fontSize: fontSize, color: AppTheme.themeConfig.primaryTextColor)),
      ],
    );
  }

  /// 设备状态文本
  Widget _buildDeviceStatusView(double fontSize) {
    var list = <Widget>[];
    list.add(Text('设备状态: ${DeviceUtils.getStatusText(monitorData?.deviceStatus)}',
        style: TextStyle(fontSize: fontSize, color: AppTheme.themeConfig.primaryTextColor)));
    // 设备状态是[离线]或者[远程关机]，就不要显示[运动]or[静止]了
    if (monitorData?.deviceStatus == 1 || monitorData?.deviceStatus == 3) {
      // 设备状态是在线或者深度休眠，就显示运动or静止
      if (monitorData?.motionStateText != null) {
        list.add(Text(', ${monitorData?.motionStateText}',
            style: TextStyle(fontSize: fontSize, color: AppTheme.themeConfig.primaryTextColor)));
      }
    }
    return Row(
      children: list,
    );
  }

  /// 根据定位模式不同，显示不同的信息
  Widget _buildLocationModeInfo() {
    // 定位模式: 1:GPS定位 2:WIFI定位 3:基站定位
    if (monitorData?.locationType == 1) {
      // GPS定位
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text('定位类型: ${LocationUtils.getLocationTypeText(monitorData?.locationType)}',
                  style: TextStyle(fontSize: 13, color: AppTheme.themeConfig.primaryTextColor)),
              const SizedBox(width: 12),
              // 速度
              Text('速度: ${monitorData?.speed ?? '0'}km/h',
                  style: TextStyle(fontSize: 13, color: AppTheme.themeConfig.primaryTextColor)),
              // 海拔，如果海拔为0就不显示
              _buildAltitudeInfo(),
            ],
          ),
        ],
      );
    } else {
      // 2:WIFI定位 3:基站定位
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('定位类型: ${LocationUtils.getLocationTypeText(monitorData?.locationType)}',
              style: TextStyle(fontSize: 13, color: AppTheme.themeConfig.primaryTextColor)),
        ],
      );
    }
  }

  /// 海拔信息
  Widget _buildAltitudeInfo() {
    if (monitorData?.altitude == 0) {
      return Container();
    }
    return Row(
      children: [
        const SizedBox(width: 12),
        Text('海拔: ${monitorData?.altitude ?? '0'}m',
            style: TextStyle(fontSize: 13, color: AppTheme.themeConfig.primaryTextColor))
      ],
    );
  }

  /// 构建地址信息
  Widget _buildAddressInfo() {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    String address = '';
    if (deviceInfo.isNineDevice == true) {
      address = nineDeviceAddress ?? '';
    } else {
      address = monitorData?.address ?? '';
    }
    return Column(
      children: [
        const SizedBox(height: 4),
        Divider(
          height: 1,
          color: ColorUtils.hexToColor('#E5E5E5'),
        ),
        const SizedBox(height: 4),
        Container(
          alignment: Alignment.centerLeft,
          child: Text(
            '地址: ${address}',
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 13,
              color: AppTheme.themeConfig.primaryTextColor,
            ),
          ),
        ),
      ],
    );
  }

  /// 计算静止时长
  /// 显示现在的时间与定位时间的时间差，并且注意，时间差小于5分钟就显示0天0小时0分钟
  String _getStaticTime() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == true) {
      return '0分钟';
    }
    // 没有经纬度，显示0分钟
    if (!hasLocation) {
      return '0分钟';
    }
    if (monitorData?.gpsTime == null) {
      return '';
    }
    final gpsTime = DateTime.parse(monitorData!.gpsTime!);
    final now = DateTime.now();
    final difference = now.difference(gpsTime);
    if (difference.inMinutes < 5) {
      return '0天0小时0分钟';
    }
    final days = difference.inDays;
    final hours = difference.inHours - days * 24;
    final minutes = difference.inMinutes - days * 24 * 60 - hours * 60;
    // days、hours大于1才显示
    if (days > 0) {
      return '${days}天${hours}小时${minutes}分钟';
    } else if (hours > 0) {
      return '${hours}小时${minutes}分钟';
    } else {
      return '${minutes}分钟';
    }
  }

  /// 根据电量值获取电量图标
  String _getBatteryImage(int? battery) {
    int batteryLevel = 0;
    if (battery == null) {
      return 'assets/images/device/battery_level_0.png';
    }
    if (battery <= 25) {
      batteryLevel = 0;
    } else if (battery <= 40) {
      batteryLevel = 1;
    } else if (battery <= 55) {
      batteryLevel = 2;
    } else if (battery <= 70) {
      batteryLevel = 3;
    } else if (battery <= 85) {
      batteryLevel = 4;
    } else if (battery <= 100) {
      batteryLevel = 5;
    }
    return 'assets/images/device/battery_level_${batteryLevel}.png';
  }

  /// 根据信号值获取信号图标
  String _getCsqLevelImage(int? csq) {
    int csqLevel = 0;
    if (csq != null) {
      if (csq <= 5) {
        csqLevel = 0;
      } else if (csq <= 8) {
        csqLevel = 1;
      } else if (csq <= 12) {
        csqLevel = 2;
      } else if (csq <= 16) {
        csqLevel = 3;
      } else if (csq <= 23) {
        csqLevel = 4;
      } else {
        csqLevel = 5;
      }
    }
    return 'assets/images/device/csq_$csqLevel.png';
  }

  /// 构建右上角按钮（结构重构）
  Widget _buildTopRightView() {
    return Positioned(
      right: 20,
      top: 20,
      child: Column(
        children: [
          // 切换图层按钮
          GestureDetector(
            onTap: () {
              // 切换标准地图和卫星图
              myMapController?.getMapType().then((value) {
                if (value == BMFMapType.Standard) {
                  myMapController?.updateMapOptions(BMFMapOptions(mapType: BMFMapType.Satellite));
                } else {
                  myMapController?.updateMapOptions(BMFMapOptions(mapType: BMFMapType.Standard));
                }
              });
            },
            child: const _SquareIconButton(
              icon: Icons.layers_outlined,
              label: '卫星地图',
            ),
          )
        ],
      ),
    );
  }

  /// 构建右下角按钮
  Widget _buildBottomRightView() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    // 设置高度
    return Positioned(
      right: 20,
      bottom: bottomViewHeight + 60,
      child: Column(
        children: [
          // 设备位置
          GestureDetector(
            onTap: () async {
              if (deviceInfo.isNineDevice == true) {
                return;
              }
              // 移动到设备位置
              myMapController?.setCenterCoordinate(
                  BMFCoordinate(monitorData?.latitude ?? 0, monitorData?.longitude ?? 0), true);
            },
            child: const _SquareAssetButton(
              asset: 'assets/images/home/XJDeviceLocation.png',
              label: '设备位置',
            ),
          ),
          const SizedBox(height: 12),
          // 手机位置
          GestureDetector(
            onTap: () async {
              if (deviceInfo.isNineDevice == true) {
                return;
              }
              // 定位到手机位置
              clickLocationType = 2;
              isLocation = true;
              await _myLocPlugin.stopLocation();
              _startLocation();
            },
            child: const _SquareAssetButton(
              asset: 'assets/images/home/XJyuanchengshezhi.png',
              label: '我的位置',
            ),
          )
        ],
      ),
    );
  }

  Widget _buildBottomView() {
    return Positioned(
        left: 16,
        right: 16,
        bottom: 16,
        child: Container(
          key: bottomViewKey,
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.white,
                Colors.white.withOpacity(0.95),
              ],
            ),
            borderRadius: BorderRadius.circular(20),
            border: Border.all(
              color: AppTheme.themeConfig.primaryColor.withOpacity(0.15),
              width: 1,
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.15),
                blurRadius: 20,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            children: [
              _buildInfoCard(),
              const SizedBox(height: 12),
              Row(
                children: [
                  Expanded(
                    flex: 3,
                    child: _buildBottomButton(
                      label: '刷新(${countDown}s)',
                      icon: Icons.refresh,
                      gradient: null,
                      bgColor: AppTheme.themeConfig.greyBgColor,
                      textColor: AppTheme.themeConfig.primaryTextColor,
                      onPressed: () => _fetchDeviceLocation(),
                    ),
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    flex: 2,
                    child: _buildBottomButton(
                      label: '轨迹',
                      icon: Icons.timeline,
                      gradient: LinearGradient(
                        colors: [Colors.orange.shade400, Colors.orange.shade600],
                      ),
                      bgColor: null,
                      textColor: Colors.white,
                      onPressed: () => context.push(RouterManager.track),
                    ),
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    flex: 2,
                    child: _buildBottomButton(
                      label: '导航',
                      icon: Icons.navigation,
                      gradient: LinearGradient(
                        colors: [
                          AppTheme.themeConfig.primaryColor,
                          AppTheme.themeConfig.primaryColor.withOpacity(0.8),
                        ],
                      ),
                      bgColor: null,
                      textColor: Colors.white,
                      onPressed: () => _navigation(),
                    ),
                  )
                ],
              )
            ],
          ),
        ));
  }

  Widget _buildBottomButton({
    required String label,
    required IconData icon,
    LinearGradient? gradient,
    Color? bgColor,
    required Color textColor,
    required VoidCallback onPressed,
  }) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 10),
        decoration: BoxDecoration(
          gradient: gradient,
          color: bgColor,
          borderRadius: BorderRadius.circular(14),
          boxShadow: gradient != null
              ? [
                  BoxShadow(
                    color: (gradient.colors.first).withOpacity(0.3),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ]
              : null,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: textColor, size: 16),
            const SizedBox(width: 4),
            Text(
              label,
              style: TextStyle(
                fontSize: 13,
                fontWeight: FontWeight.w600,
                color: textColor,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 导航（重命名）
  void _openNavigationSheet() async {
    final availableMaps = await MapLauncher.installedMaps;
    XLogger.info(availableMaps);
    if (availableMaps.isNotEmpty) {
      // 显示bottomSheet
      _showMapSheet(availableMaps);
    } else {
      ToastUtils.showToast('没有安装地图软件');
    }
  }

  // 兼容旧方法名
  void _navigation() async { _openNavigationSheet(); }

  /// 显示地图选择
  _showMapSheet(List<AvailableMap> availableMaps) {
    final mapTitleMap = {
      'amap': '高德地图',
      'baidu': '百度地图',
      'google': '谷歌地图',
      'apple': '苹果地图',
      'google': '谷歌地图',
      'tencent': '腾讯地图',
    };
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          height: availableMaps.length * 60,
          child: ListView.builder(
            itemCount: availableMaps.length,
            itemBuilder: (BuildContext context, int index) {
              final map = availableMaps[index];
              final mapName = mapTitleMap[map.mapType.name.toLowerCase()] ?? map.mapName;
              return ListTile(
                onTap: () {
                  map.showDirections(
                      destination: Coords(monitorData?.latitude ?? 0, monitorData?.longitude ?? 0),
                      destinationTitle: monitorData?.address ?? '');
                  // map.showMarker(
                  //   coords: Coords(monitorData?.latitude ?? 0, monitorData?.longitude ?? 0),
                  //   title: monitorData?.address ?? '',
                  // );
                  Navigator.pop(context);
                },
                title: Text(mapName),
              );
            },
          ),
        );
      },
    );
  }

  BaiduLocationAndroidOption initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        // 定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        locationMode: BMFLocationMode.hightAccuracy,
        // 是否需要返回地址信息
        isNeedAddress: true,
        // 是否需要返回海拔高度信息
        isNeedAltitude: true,
        // 是否需要返回周边poi信息
        isNeedLocationPoiList: true,
        // 是否需要返回新版本rgc信息
        isNeedNewVersionRgc: true,
        // 是否需要返回位置描述信息
        isNeedLocationDescribe: true,
        // 是否使用gps
        openGps: true,
        // 可选，设置场景定位参数，包括签到场景、运动场景、出行场景
        locationPurpose: BMFLocationPurpose.sport,
        // 坐标系
        coordType: BMFLocationCoordType.gcj02,
        // 设置发起定位请求的间隔，int类型，单位ms
        // 如果设置为0，则代表单次定位，即仅定位一次，默认为0
        scanspan: 5000);
    return options;
  }

  BaiduLocationIOSOption initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
      // 坐标系
      coordType: BMFLocationCoordType.gcj02,
      // 位置获取超时时间
      locationTimeout: 10,
      // 获取地址信息超时时间
      reGeocodeTimeout: 10,
      // 应用位置类型 默认为automotiveNavigation
      activityType: BMFActivityType.automotiveNavigation,
      // 设置预期精度参数 默认为best
      desiredAccuracy: BMFDesiredAccuracy.best,
      // 是否需要最新版本rgc数据
      isNeedNewVersionRgc: true,
      // 指定定位是否会被系统自动暂停
      pausesLocationUpdatesAutomatically: false,
      // 指定是否允许后台定位,
      // 允许的话是可以进行后台定位的，但需要项目
      // 配置允许后台定位，否则会报错，具体参考开发文档
      allowsBackgroundLocationUpdates: true,
      // 设定定位的最小更新距离
      distanceFilter: 10,
    );
    return options;
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      timerUtil.setOnTimerTickCallback((int value) {
        XLogger.debug('倒计时：${value ~/ 1000}');
        setState(() {
          countDown = (value ~/ 1000);
        });
        if (countDown == 0) {
          _fetchDeviceLocation();
        }
      });
      final bottomViewHeight = bottomViewKey.currentContext?.size?.height ?? 120;
      XLogger.debug('bottomViewHeight: $bottomViewHeight');
      setState(() {
        this.bottomViewHeight = bottomViewHeight;
      });
      // 获取设备定位
      // _fetchDeviceLocation();
    });
    super.initState();
    PermissionManager.requestLocationPermissions(
      context,
      onPermissionDenied: () {
        ToastUtils.showSimpleDialog(context,
            title: '提示',
            content: '请开启定位权限',
            cancelTitle: '取消',
            confirmTitle: '去设置',
            showCancel: true, cancelCallback: () {
          Navigator.pop(context);
        }, confirmCallback: () {
          Navigator.pop(context);
          PermissionManager.openSettings();
        });
      },
    );
    if (Platform.isIOS) {
      //接受定位回调
      _myLocPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        _locationSuccess(result);
      });
    } else if (Platform.isAndroid) {
      //接受定位回调
      _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        _locationSuccess(result);
      });
    }
    _locationAction();
  }

  void _locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    Map iosMap = initIOSOptions().getMap();
    Map androidMap = initAndroidOptions().getMap();

    await _myLocPlugin.prepareLoc(androidMap, iosMap);
  }

  /// 开始定位
  void _startLocation() async {
    if (Platform.isIOS) {
      var result = await _myLocPlugin.singleLocation({'isReGeocode': true, 'isNetworkState': true});
      XLogger.debug('开始单次定位：${result}');
    } else if (Platform.isAndroid) {
      await _myLocPlugin.startLocation();
    }
  }

  /// 定位成功
  void _locationSuccess(BaiduLocation result) {
    //result为定位结果
    XLogger.debug('定位结果：longitude:${result.longitude}, latitude:${result.latitude}, address:${result.address}');
    phoneLocation = BMFCoordinate(result.latitude!, result.longitude!);
    if (isLocation) {
      isLocation = false;
      myMapController?.setCenterCoordinate(BMFCoordinate(result.latitude!, result.longitude!), true);
      // _myLocPlugin.stopLocation();
    }
    if (clickLocationType == 1) {
      _drawDeviceMarker(result.latitude!, result.longitude!);
      return;
    } else if (clickLocationType == 0 && !hasLocation) {
      monitorData?.longitude = result.longitude;
      monitorData?.latitude = result.latitude;
      monitorData?.address = result.address;
      phoneAddress = result.address;
      _drawDeviceMarker(monitorData!.latitude!, monitorData!.longitude!);
      return;
    }
    XLogger.debug('result.course: ${result.course}');
    BMFLocation location = BMFLocation(
      coordinate: BMFCoordinate(result.latitude!, result.longitude!),
      altitude: result.altitude,
      horizontalAccuracy: result.radius,
      verticalAccuracy: result.verticalAccuracy,
      speed: result.speed,
      course: result.course,
    );
    BMFUserLocation userLocation = BMFUserLocation(
      location: location,
    );
    myMapController?.updateLocationData(userLocation);
    // 更新样式
    BMFUserLocationDisplayParam displayParam = BMFUserLocationDisplayParam(
      accuracyCircleFillColor: Colors.blue,
      accuracyCircleStrokeColor: Colors.red,
      isAccuracyCircleShow: true,
      locationViewOffsetX: 0,
      locationViewOffsetY: 0,
      locationViewImage: 'assets/images/map/phone_location.png',
      locationViewHierarchy: BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_BOTTOM,
    );
    myMapController?.updateLocationViewWithParam(displayParam);
  }

  @override
  void dispose() {
    timerUtil.cancel();
    _myLocPlugin.stopLocation();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final deviceInfo = ref.watch(deviceInfoProvider);
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(kAppbarHeight),
        child: AppBar(
          title: Text(
            '查看定位(${deviceInfo.imei})',
            style: const TextStyle(
              fontSize: 17,
              color: Colors.white,
            ),
          ),
          centerTitle: true,
          backgroundColor: AppTheme.themeConfig.primaryColor,
          foregroundColor: Colors.white,
          iconTheme: const IconThemeData(color: Colors.white),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ),
      ),
      body: Stack(
        children: [
          BMFMapWidget(
            onBMFMapCreated: (controller) {
              onBMFMapCreated(controller);
            },
            mapOptions: mapOptions,
          ),
          _buildBottomView(),
          _buildTopRightView(),
          _buildBottomRightView(),
          // 统一方形按钮风格，抽离成组件
        ],
      ),
    );
  }
}

class _SquareIconButton extends StatelessWidget {
  final IconData icon;
  final String label;
  const _SquareIconButton({required this.icon, required this.label});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.white,
            Colors.white.withOpacity(0.9),
          ],
        ),
        borderRadius: BorderRadius.circular(14),
        border: Border.all(
          color: AppTheme.themeConfig.primaryColor.withOpacity(0.2),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: const EdgeInsets.all(6),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                  AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                ],
              ),
              shape: BoxShape.circle,
            ),
            child: Icon(
              icon,
              color: AppTheme.themeConfig.primaryColor,
              size: 18,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.w600,
              color: AppTheme.themeConfig.primaryTextColor,
            ),
          )
        ],
      ),
    );
  }
}

class _SquareAssetButton extends StatelessWidget {
  final String asset;
  final String label;
  const _SquareAssetButton({required this.asset, required this.label});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.white,
            Colors.white.withOpacity(0.9),
          ],
        ),
        borderRadius: BorderRadius.circular(14),
        border: Border.all(
          color: AppTheme.themeConfig.primaryColor.withOpacity(0.2),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: const EdgeInsets.all(6),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                  AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                ],
              ),
              shape: BoxShape.circle,
            ),
            child: Image.asset(
              asset,
              width: 20,
              height: 20,
              fit: BoxFit.contain,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.w600,
              color: AppTheme.themeConfig.primaryTextColor,
            ),
          )
        ],
      ),
    );
  }
}
